#pragma region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU Lesser General Public License.
/// </copyright>
#pragma endregion

#pragma once

class WindowHookHandle
{
private:
	HHOOK _hook;

public:

	WindowHookHandle() : _hook(NULL)
	{
	}

	~WindowHookHandle()
	{
		Dettach();
	}

	operator HHOOK() const throw()
	{ 
		return _hook; 
	}

	void Attach(HOOKPROC proc, HWND hWnd = NULL, int idHook = WH_CALLWNDPROC)
	{
		ATLASSERT(_hook == NULL);
		if(_hook != NULL) Dettach();

		DWORD threadId = ::GetCurrentThreadId();
		if(hWnd != NULL)
		{
			ATLASSERT(::IsWindow(hWnd));
			threadId = ::GetWindowThreadProcessId(hWnd, NULL);
		}

		ATLASSERT(threadId != NULL);
		_hook = ::SetWindowsHookEx(idHook, proc, NULL, threadId);
	}

	void Dettach()
	{
		if(_hook != NULL)
		{
			::UnhookWindowsHookEx(_hook);
			_hook = NULL;
		}
	}
};

